//
//  ICENavigatorBar.m
//  ICEH5Bridge
//
//  Created by wujianrong on 2017/8/15.
//  Copyright © 2017年 wanda. All rights reserved.
//

#import "ICENavigatorBar.h"
#import "ICECore.h"
#import "ICEUI.h"

@implementation ICENavViewConfig


@end

@interface ICENavigatorBar()
@property(nonatomic, strong) UIButton* leftBtn;
@property(nonatomic, strong) UIButton* rightBtn;
@property(nonatomic, strong) UIButton* titleBtn;
@property (nonatomic, strong) UILabel* titleLabel;
@property(nonatomic, strong) UILabel* leftLabel;
@property(nonatomic, strong) UILabel* rightLabel;
@property(nonatomic, strong) UIImageView* backImageView;
//@property(nonatomic, strong) NSMutableArray* configArray;

@property(nonatomic, strong) UIView* lineBreakView;

@end

@implementation ICENavigatorBar

-(UILabel*)makeLabelOrigin:(CGPoint)origin Text:(NSString*)text fontSize:(CGFloat)fontSize textColor:(UIColor *)textColor
{
    UILabel* lb = [[UILabel alloc] initWithFrame:CGRectMake(origin.x, origin.y, 0, 0)];
    if (self) {
        //self.backgroundColor = [UIColor clearColor];
        if (text == nil) {
            text = @"";
        }
        UIFont* labelFont = [UIFont iceFontWithFontName:nil displayStr:text fontSize:fontSize];
        lb.font = labelFont;
        lb.text = text;
        lb.textAlignment = NSTextAlignmentLeft;
        if (textColor) {
            lb.textColor = textColor;
        }
        [lb iceModifySize:labelFont.iceFontSize];
        if(fontSize < 15)
        {
            [lb setFrame:CGRectIntegral(lb.frame)];
        }
    }
    return lb;
    
}

- (void)setupUI
{
    if (_config == nil) {
        _config = [[ICENavViewConfig alloc]init];
        _config.backImageName = @"icon_arrow_left@3x";
        _config.leftColor = ICERGB_E(0x3f4750);
        _config.leftiSize = 17;
        
        _config.rightSize = 16;
        _config.rightColor = ICERGB_E(0x3f4750);
        _config.titleSize = 18;
        _config.titleColor =  ICERGB_E(0x3f4750);
        _config.backGroundColor = [UIColor whiteColor];
    }
    self.titleLabel = [self makeLabelOrigin:CGPointZero Text:@" " fontSize:_config.titleSize textColor:_config.titleColor];
    
    
    [self.titleLabel iceFitToHorizontalCenterWithView:self];
    [self.titleLabel iceModifyCenterY:(20+22)];
    
    _backImageView = [[UIImageView alloc]init];
    [self addSubview:_backImageView];
    [_backImageView iceModifyBottem:ICE_VB(self)-10];
    
    NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"ICEH5Resourse.bundle"];
    
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    UIImage* image =  [UIImage imageWithContentsOfFile:[bundle pathForResource:_config.backImageName ofType:@"png"]];
    
    _backImageView.image = image;
    [_backImageView iceModifyWidth:image.size.width];
    [_backImageView iceModifyHeight:image.size.height];
    [_backImageView iceModifyX:0];
    [_backImageView iceModifyBottem:ICE_VB(self)-10];
    
    self.leftLabel = [self makeLabelOrigin:CGPointZero Text:@" " fontSize:_config.leftiSize textColor:_config.leftColor];
    self.rightLabel = [self makeLabelOrigin:CGPointZero Text:@" " fontSize:_config.rightSize textColor:_config.rightColor];
    
    _leftBtn = [[UIButton alloc]initWithFrame:_leftLabel.frame];
    _leftBtn.backgroundColor = [UIColor clearColor];
    
    
    _rightBtn = [[UIButton alloc]initWithFrame:_rightLabel.frame];
    _rightBtn.backgroundColor = [UIColor clearColor];
    
    
    _titleBtn = [[UIButton alloc]initWithFrame:_titleLabel.frame];
    _titleBtn.backgroundColor = [UIColor clearColor];
    
    _lineBreakView = [[UIView alloc]initWithFrame:CGRectMake(0, ICE_VB(self)-0.5, ICE_VW(self), 0.5)];
    _lineBreakView.backgroundColor = ICEGRAY(0x87);
    
    [self addSubview:_leftLabel];
    [self addSubview:_titleLabel];
    [self addSubview:_rightLabel];
    
    [self addSubview:_titleBtn];
    [self addSubview:_rightBtn];
    [self addSubview:_leftBtn];
    [self updateButtons];
    [self setLeftNavigationItemWithStr:@" " right:@" " title:@" " status:nil];
    
    [_leftBtn addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)updateButtons
{
    [self addSubview:_lineBreakView];
    
    self.backgroundColor = _config.backGroundColor;
    
    
    [_leftLabel iceModifyBottem:ICE_VB(self)-10];
    [_rightLabel iceModifyBottem:ICE_VB(self)-10];
    [_titleLabel iceModifyBottem:ICE_VB(self)-10];
    
    _leftBtn.frame = _leftLabel.frame;
    [_leftBtn iceModifyWidth:ICE_VW(_leftLabel)+24];
    [_leftBtn iceModifyHeight:ICE_VH(_leftLabel)+16];
    _leftBtn.center = _leftLabel.center;
    
    _rightBtn.frame = _rightLabel.frame;
    [_rightBtn iceModifyWidth:ICE_VW(_rightLabel)+20];
    [_rightBtn iceModifyHeight:ICE_VH(_rightLabel)+16];
    _rightBtn.center = _rightLabel.center;
    
    
    _titleBtn.frame = _titleLabel.frame;
    [_titleBtn iceModifyWidth:ICE_VW(_titleLabel)+10];
    [_titleBtn iceModifyHeight:ICE_VH(_titleLabel)+10];
    _titleBtn.center = _titleLabel.center;
    
    if (ICE_VL(_backImageView) > 3) {
        _leftBtn.frame = _backImageView.frame;
        [_leftBtn iceModifyWidth:ICE_VW(_backImageView)+10];
        [_leftBtn iceModifyHeight:ICE_VH(_backImageView)+10];
        _leftBtn.center = _backImageView.center;
    }
    
}

- (void)leftAction:(id)sender
{
    _leftClickBlock();
}

- (void)rightAction:(id)sender
{
    _rightClickBlock();
}

-(void)setBackWithTitle:(NSString*)title
{
    _leftLabel.text = @"";
    [_backImageView iceModifyX:12];
    _leftBtn.frame = _backImageView.frame;
    [_leftBtn iceModifyWidth:ICE_VW(_backImageView)+24];
    [_leftBtn iceModifyHeight:ICE_VH(_backImageView)+16];
    _leftBtn.center = _backImageView.center;
}

-(void)labelrefreshWithLabel:(UILabel*)label origin:(CGPoint)origin Text:(NSString *)text fontSize:(CGFloat)fontSize textColor:(UIColor *)textColor
{
    if (ICESafeString(text).length == 0) {
        return;
    }
    [label iceModifyOrigi:origin];
    label.text = text;
    UIFont* labelFont = [UIFont iceFontWithFontName:nil displayStr:text fontSize:fontSize];
    label.font = labelFont;
    
    if (textColor) {
        label.textColor = textColor;
    }
    [label iceModifySize:labelFont.iceFontSize];
    if(fontSize < 15)
    {
        [label setFrame:CGRectIntegral(label.frame)];
    }
}

-(void)setLeftNavigationItemWithStr:(NSString*)left right:(NSString*)right title:(NSString*)title status:(NSString*)status;
{
    
    if (left.length > 0) {
        [_backImageView iceModifyRight:0];
        [self labelrefreshWithLabel:_leftLabel origin:CGPointMake(12, 10) Text:left fontSize:_config.leftiSize textColor:_config.leftColor];
    }
    //    else
    //    {
    //        [_backImageView iceModifyX:12];
    //        [_backImageView iceModifyBottem:ICE_VB(self)-10];
    //    }
    
    if (right.length > 0) {
        [self labelrefreshWithLabel:_rightLabel origin:CGPointMake(12, 10) Text:right fontSize:_config.rightSize textColor:_config.rightColor];
        [_rightLabel iceModifyRight:ICE_VW(self)-10];
    }
    
    if (title.length > 0) {
        CGFloat leftImagP = ICE_VR(_backImageView) > ICE_VR(_leftLabel) ? ICE_VR(_backImageView) : ICE_VR(_leftLabel);
        CGFloat rightP = ICE_VL(_rightLabel);
        CGFloat gap = rightP - leftImagP;
        [self labelrefreshWithLabel:_titleLabel origin:CGPointMake(12, 10) Text:title fontSize:_config.titleSize textColor:_config.titleColor];
        if (gap - ICE_VW(_titleLabel) < 16) {
            [_titleLabel iceModifyWidth:gap - 16];
        }
        _titleLabel.center = self.center;
    }
    [self updateButtons];
}


@end


#pragma mark - CAAnimationDelegate Wrapper
@interface ICEAnimationDelegateWrapper : NSObject<CAAnimationDelegate>

@property (weak, nonatomic) id<CAAnimationDelegate> delegate;

@end

@implementation ICEAnimationDelegateWrapper

- (instancetype)initWithDelegate:(id<CAAnimationDelegate>)delegate {
    if (self = [self init]) {
        self.delegate = delegate;
    }
    return self;
}

#pragma mark - CAAnimationDelegate

- (void)animationDidStart:(CAAnimation *)anim {
    if ([_delegate respondsToSelector:@selector(animationDidStart:)]) {
        [_delegate animationDidStart:anim];
    }
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if ([_delegate respondsToSelector:@selector(animationDidStop:finished:)]) {
        [_delegate animationDidStop:anim finished:flag];
    }
}

@end

#pragma mark - WDPWebViewProgressBar

typedef void(^ICEWebViewProgressBarCompletionBlock)(void);

@interface ICEWebViewProgressBar()<CAAnimationDelegate>
@property (strong, nonatomic) id<CAAnimationDelegate> animationDelegate;
@property (strong, nonatomic) UIColor *progressColor;
@property (strong, nonatomic) UIColor *remainColor;
@property (strong, nonatomic) CAGradientLayer *progressLayer;
@property (strong, nonatomic) CABasicAnimation *finalAnimation;
@property (strong, nonatomic) ICEWebViewProgressBarCompletionBlock finalCompletionBlock;
@end

@implementation ICEWebViewProgressBar

#define kProgressBarWidthKeyPath @"bounds.size.width"
//ICEDefLiteralString(kWDPWebViewProgressBarAnimationKey)
static NSString * const kICEWebViewProgressBarAnimationKey = @"kICEWebViewProgressBarAnimationKey";

static CGFloat iceWebViewProgressBarHeight = 3.0f;
+ (void)configDefaultProgressHeight:(CGFloat)height {
    iceWebViewProgressBarHeight = height;
}

static UIColor *iceWebViewProgressBarColor;
+ (void)configDefaultProgressColor:(UIColor *)progressColor {
    iceWebViewProgressBarColor = progressColor;
}

static UIColor *iceWebViewProgressBarRemainColor;
+ (void)configDefaultRemainColor:(UIColor *)remainColor {
    iceWebViewProgressBarRemainColor = remainColor;
}

static NSArray *iceWebViewProgressBarDurations;
static NSArray *iceWebViewProgressBarProgresses;
+ (void)configAnimationWithDurations:(NSArray *)durations progresses:(NSArray *)progresses {
    
    if (durations.count == 0 || progresses.count == 0 || durations.count != progresses.count) {
        //DebugLog(@"Warning: durations or progress are not valid!");
        return;
    }
    iceWebViewProgressBarDurations = [durations copy];
    iceWebViewProgressBarProgresses = [progresses copy];
}

static CGFloat iceWebViewProgressBarFinalAnimationDuration = 0.5f;
+ (void)configDefaultFinalAnimationDuration:(CFTimeInterval)duration {
    iceWebViewProgressBarFinalAnimationDuration = duration;
}

static NSArray *iceWebViewProgressBarTimingFunctions;
static NSString *iceWebViewProgressBarFinalTimingFunction;
+ (void)configDefaultTimingFunctions:(NSArray *)tfs finalTimingFunction:(NSString *)finalTF {
    iceWebViewProgressBarTimingFunctions = [tfs copy];
    iceWebViewProgressBarFinalTimingFunction = [finalTF copy];
}

+(void)load
{
    [ICEWebViewProgressBar configDefaultProgressColor:ICERGB_E(0x2AC0F3)];
    [ICEWebViewProgressBar configAnimationWithDurations:@[@4, @10, @10] progresses:@[@0.6, @0.85, @0.95]];
    [ICEWebViewProgressBar configDefaultTimingFunctions:@[kCAMediaTimingFunctionEaseOut, kCAMediaTimingFunctionLinear, kCAMediaTimingFunctionLinear] finalTimingFunction:kCAMediaTimingFunctionEaseIn];
}

- (instancetype)init {
    
    if (self = [super init]) {
        
        _animationDelegate = [[ICEAnimationDelegateWrapper alloc] initWithDelegate:self];
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    
    [self configFrame];
    
    self.clipsToBounds = YES;
    
    _progressLayer = [CAGradientLayer layer];
    
    [self.layer addSublayer:_progressLayer];
    [self resetProgressBarToInitialValue];
    
    [self configColor];
    [self configAnimation];
}

- (void)configFrame {
    self.frame = CGRectMake(0, 0, ICESCREEN_WIDTH, iceWebViewProgressBarHeight);
}

- (void)configColor {
    if (iceWebViewProgressBarColor) {
        [self setProgressColor:iceWebViewProgressBarColor];
    }
    if (!_progressColor) {
        [self setProgressColor:[UIColor orangeColor]];
    }
    if (iceWebViewProgressBarRemainColor) {
        [self setRemainColor:iceWebViewProgressBarRemainColor];
    }
    if (!_remainColor) {
        [self setRemainColor:[UIColor clearColor]];
    }
    [self setGradientColors:nil];
}

- (void)configAnimation {
    if (!iceWebViewProgressBarDurations || !iceWebViewProgressBarProgresses) {
        iceWebViewProgressBarDurations = @[@10, @10, @10];
        iceWebViewProgressBarProgresses = @[@(0.6f), @(0.85f), @(0.95)];
    }
    if (!iceWebViewProgressBarTimingFunctions) {
        iceWebViewProgressBarTimingFunctions = @[kCAMediaTimingFunctionLinear, kCAMediaTimingFunctionLinear, kCAMediaTimingFunctionLinear];
    }
    if (!iceWebViewProgressBarFinalTimingFunction) {
        iceWebViewProgressBarFinalTimingFunction = kCAMediaTimingFunctionEaseIn;
    }
}

- (CABasicAnimation *)makeAnimation:(CFTimeInterval)duration toProgress:(CGFloat)to {
    
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:kProgressBarWidthKeyPath];
    anim.toValue = @(self.frame.size.width * 2 * to);
    anim.fillMode = kCAFillModeForwards;
    anim.removedOnCompletion = NO;
    anim.duration = duration;
    anim.delegate = _animationDelegate;
    return anim;
}

- (CABasicAnimation *)makeFinalAnimation {
    CABasicAnimation *anim = [self makeAnimation:iceWebViewProgressBarFinalAnimationDuration toProgress:1.0];
    anim.fromValue = [_progressLayer.presentationLayer valueForKeyPath:kProgressBarWidthKeyPath];
    anim.timingFunction = [CAMediaTimingFunction functionWithName:iceWebViewProgressBarFinalTimingFunction];
    return anim;
}

- (void)setProgressColor:(UIColor *)progressColor {
    _progressColor = progressColor;
    _progressLayer.backgroundColor = _progressColor.CGColor;
}

- (void)setRemainColor:(UIColor *)remainColor {
    _remainColor = remainColor;
    self.layer.backgroundColor = _remainColor.CGColor;
}

- (void)setGradientColors:(NSArray *)gradientColors{
    NSArray *colors = gradientColors;
    if (!colors) {
        colors = @[(__bridge id)ICERGB_E(0x80C8FC).CGColor, (__bridge id)ICERGB_E(0x327FE6).CGColor];
    }
    _progressLayer.colors = colors;
    _progressLayer.locations = @[@0.7,@0.95];
    _progressLayer.startPoint = CGPointMake(0, 0);
    _progressLayer.endPoint = CGPointMake(1.0, 0);
}

- (void)startAnimation {
    
    NSUInteger count = iceWebViewProgressBarDurations.count;
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:kProgressBarWidthKeyPath];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    
    // set values
    NSMutableArray *values = [NSMutableArray arrayWithObject:@(0)];
    for (NSUInteger i = 0; i < count; i++) {
        [animation setValues:values];
        CGFloat progress = [iceWebViewProgressBarProgresses[i] floatValue];
        [values addObject:@(self.frame.size.width * 2 * progress)];
    }
    animation.values = values;
    
    // set duration
    CFTimeInterval duration = 0;
    for (NSNumber *t in iceWebViewProgressBarDurations) {
        duration += [t doubleValue];
    }
    animation.duration = duration;
    
    // set keyTimes
    CGFloat cumTime = 0;
    NSMutableArray *keyTimes = [NSMutableArray arrayWithObject:@(0)];
    for (NSNumber *t in iceWebViewProgressBarDurations) {
        cumTime = cumTime + [t doubleValue] / duration;
        [keyTimes addObject:@(cumTime)];
    }
    animation.keyTimes = keyTimes;
    
    // set timingFuntions
    NSMutableArray *tfs = [NSMutableArray array];
    for (NSUInteger i = 0; i < count; i++) {
        NSString *tfName = iceWebViewProgressBarTimingFunctions[i];
        CAMediaTimingFunction *function = [CAMediaTimingFunction functionWithName:tfName];
        [tfs addObject:function];
    }
    animation.timingFunctions = tfs;
    
    [_progressLayer addAnimation:animation forKey:kICEWebViewProgressBarAnimationKey];
    
}


- (void)finishAnimation {
    __weak typeof(self) Weakself = self;
    ICEWebViewProgressBarCompletionBlock completionBlock = ^{
        [Weakself resetProgressBarToInitialValue];
        [Weakself.progressLayer removeAllAnimations];
    };
    
    _finalCompletionBlock = completionBlock;
    
    CABasicAnimation *anim = [self makeFinalAnimation];
    anim.beginTime = CACurrentMediaTime();
    _finalAnimation = anim;
    
    [_progressLayer addAnimation:anim forKey:nil];
}

- (void)resetProgressBarToInitialValue {
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    _progressLayer.bounds = CGRectMake(0, self.frame.size.height / 2, 0, self.frame.size.height);
    [CATransaction commit];
}

#pragma mark - CAAnimationDelegate

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    // DebugLog(@"animationDidStop: %@", @(flag));
    if (!flag) {
        return;
    }
    
    if (_finalAnimation.beginTime == anim.beginTime) {
        _finalCompletionBlock();
    }
}

@end

